/**
 * Created by sufan on 2016/6/20.
 */
(function() {
    var mapUrls={
        baseMap:"http://gist.sz95000.com/tiles/wmts",
        editMap:{
            url:"http://192.168.0.6:9898/geoserver/ssjc_pro/wfs",
            layers:{
                layerNames:["ssjc_pro_line","ssjc_pro_point","ssjc_pro_polygon"],
                geometryType:
                {
                    line:["ssjc_pro_line"],
                    point:["ssjc_pro_point"],
                    polygon:["ssjc_pro_polygon"],
                }
            },
            queryFieldName:"projectid",
            featureNS:"http://192.168.0.6:9898/ssjc_pro",
            featurePrefix:"ssjc_pro",
        },
        queryMap:{
            url:"http://192.168.0.6:9898/geoserver/szroad/wfs",
            layers:{
                layerNames: ['ptroad'],
                geometryType:
                {
                    line:["ptroad"],
                    point:[],
                    polygon:[],
                }
            },
            queryFieldName:"name",
            featureNS:" http://192.168.0.50:9898/szroad",
            featurePrefix:"szroad",
        }
    }
    //添加地图
    var projection = ol.proj.get('EPSG:3857');
    var projectionExtent = projection.getExtent();
    var size = ol.extent.getWidth(projectionExtent) / 256;
    var resolutions = new Array();
    var matrixIds = new Array();
    for (var z = 0; z < 18; ++z) {
        resolutions[z] = size / Math.pow(2, z);
        matrixIds[z] = 'EPSG:900913:' + z;
    }
    //GIST 基础地图资源
    var source_reproduction = new ol.source.WMTS({
        url: mapUrls.baseMap,
        matrixSet: 'EPSG:900913',
        format: 'image/png',
        projection: projection,
        layer: "vector",
        tileGrid: new ol.tilegrid.WMTS({
            origin: ol.extent.getTopLeft(projectionExtent),
            resolutions: resolutions,
            matrixIds: matrixIds
        }),
        tileLoadFunction: function (imageTile, src) {
            var index = src.indexOf("?");
            var hash = src.slice(index).toUpperCase();
            imageTile.getImage().src = src.slice(0, index) + hash;

        },
        style: 'default',
        wrapX: true
    });
    //当前已有的数据
    var inputval = $('#inputval').val();
    //属性数据
    var inputAttri = $('#jsondata').val();
    var attributjson;
    if (inputAttri) {
        attributjson = JSON.parse(inputAttri);
    }
    //是否开启编辑
    var inputState = $('#viewOnly').val();
    var isedit;
    if (inputState) {
        isedit = JSON.parse(inputState);
    }
    var geojsonObject;
    //将绘制的要素传回后端
    var geojsonformart = new ol.format.GeoJSON();
    if (window.parent.document.getElementById(inputval)) {
        geojsonObject = window.parent.document.getElementById(inputval).value;
    }
    //地图符号
    var image = new ol.style.Circle({
        radius: 5,
        fill: null,
        stroke: new ol.style.Stroke({color: 'red', width: 3})
    });
    var mainstyle = {
        'Point': new ol.style.Style({
            image: image
        }),
        'MultiPoint': new ol.style.Style({
            image: image
        }),
        'LineString': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'red',
                width: 3
            })
        }),
        'MultiLineString': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'red',
                width: 3
            })
        }),
        'Polygon': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'red',
                lineDash: [4],
                width: 3
            }),
            fill: new ol.style.Fill({
                color: 'rgba(0, 0, 255, 0.1)'
            })
        }),
        'MultiPolygon': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'red',
                lineDash: [4],
                width: 3
            }),
            fill: new ol.style.Fill({
                color: 'rgba(0, 0, 255, 0.1)'
            })
        })
    };
    //路网符号
    var styleFunction = function (feature) {
        return mainstyle[feature.getGeometry().getType()];
    };
    //获取属性信息
    var propertyData={length:0};
    if($('#proid').val()){
        propertyData.projectid=$('#proid').val();
        propertyData.length++;
    };
    if($('#procode').val()){
        propertyData.projectcode=$('#procode').val();
        propertyData.length++;
    };
    if($('#proname').val()){
        propertyData.projectname=$('#proname').val();
        propertyData.length++;
    };
    if($('#protype').val()){
        propertyData.projecttype=$('#protype').val();
        propertyData.length++;
    };
    if($('#projectyear').val()){
        propertyData.projectyear=$('#projectyear').val();
        propertyData.length++;
    };
    if($('#projectclass').val()){
        propertyData.projectclass=$('#projectclass').val();
        propertyData.length++;
    };
    if($('#regioncode').val()){
        propertyData.regioncode=$('#regioncode').val();
        propertyData.length++;
    };
    if(propertyData.length!=7){
      alert("获取相关参数失败!");
        return;
    }

    var featruesVector = new ol.Collection();
    //构建矢量图层
    var vectSource = new ol.source.Vector({
        wrapX: false,
        features: featruesVector
    });
    var vector = new ol.layer.Vector({
        style: styleFunction,
        source: vectSource
    });
    var map = new ol.Map({
        layers: [
            new ol.layer.Tile({
                opacity: 0.7,
                source: source_reproduction,
                extent: ol.proj.transformExtent([112.6920, 21.2389, 115.6737, 24.0274], 'EPSG:4326', 'EPSG:3857')
            }), vector],
        target: 'map',
        logo: false,
        view: new ol.View({
            center: vectSource.getFeatures().length > 0 ? ol.extent.getCenter(vectSource.getExtent()) : ol.proj.transform([114.156, 22.614], 'EPSG:4326', 'EPSG:3857'),
            zoom: 11,
            extent: vectSource.getFeatures().length > 0 ? vectSource.getExtent() : ol.proj.transformExtent([113.6920, 22.2389, 114.6737, 23.0274], 'EPSG:4326', 'EPSG:3857'),
            projection: 'EPSG:3857',
            maxZoom: 18,
            minZoom: 7
        })
    });
    //如果存在矢量数据，则初始就加载
    var f = ol.format.ogc.filter;
    var featureRequest = new ol.format.WFS().writeGetFeature({
        srsName: 'EPSG:4326',
        featureNS: mapUrls.editMap.featureNS,
        featurePrefix: mapUrls.editMap.featurePrefix,
        featureTypes: mapUrls.editMap.layers.layerNames,
        outputFormat: 'application/json',
        filter: f.equalTo(mapUrls.editMap.queryFieldName, propertyData.projectid)
    });
    // post请求，并根据请求的数据进行加载
    fetch(mapUrls.editMap.url, {
        method: 'POST',
        body: new XMLSerializer().serializeToString(featureRequest)
    }).then(function(response) {
        return response.json();
    }).then(function(json) {
        var features = new ol.format.GeoJSON().readFeatures(json,{featureProjection: 'EPSG:3857',dataProjection:"EPSG:4326"});
        if(features.length>0) {
            vectSource.addFeatures(features);
            map.getView().fit(vectSource.getExtent(), (map.getSize()));
        }
    });
     var editFeatures={
         point:{
             addFeaures:[],
             deleteFeatures:[],
             editeFeatures:[]
         },
         line:{
             addFeaures:[],
             deleteFeatures:[],
             editeFeatures:[]
         },
         polygon:{
             addFeaures:[],
             deleteFeatures:[],
             editeFeatures:[]
         }
     };
    //选择工具
    var select = new ol.interaction.Select({
        wrapX: false,
        multi:true,
    });
    //编辑工具
    var draw;
    var modify = new ol.interaction.Modify({
        features: select.getFeatures(),
        wrapX: false,
        deleteCondition: function (event) {
            return ol.events.condition.shiftKeyOnly(event) &&
                ol.events.condition.singleClick(event);
        },
    });
    //修改结束后事件
    modify.on("modifyend",function(e){
            var modifyFeatures= e.features;
        if(modifyFeatures.getLength()>0){
            for(var i=0;i<modifyFeatures.getLength();i++) {
                var mfeature=modifyFeatures.getArray()[i];
               if(!mfeature.get("data-edittype")&&mfeature.get("data-edittype")=="newadd"){}
                else {
                   switch (mfeature.getGeometry().getType()) {
                       case "Point":
                       case "MultiPoint":
                           editFeatures.point.editeFeatures.push(mfeature);
                           break;
                       case "LineString":
                       case "LinearRing":
                       case "MultiLineString":
                           editFeatures.line.editeFeatures.push(mfeature);
                           break;
                       case "Polygon":
                       case "MultiPolygon":
                           editFeatures.polygon.editeFeatures.push(mfeature);
                           break;
                   }
               }
            }
        }
    });

    function addInteraction(value) {
        if (value !== 'None') {
            draw = new ol.interaction.Draw({
                source: vectSource,
                type: (value),
                freehandCondition:	function(event) {
                    return ol.events.condition.click(event)
                }
            });
            draw.on("drawend", function (e) {
                var drawfeatures = e.feature;
                if (drawfeatures) {
                    drawfeatures.setStyle(mainstyle[drawfeatures.getGeometry().getType()]);
                    drawfeatures.setId(newGuid());
                    //设置添加数据的属性信息
                    for(var key in propertyData) {
                        if(key!="length") {
                            drawfeatures.set(key,propertyData[key]);
                        }
                    }
                    drawfeatures.set('geom',drawfeatures.getGeometry());
                    drawfeatures.set("data-edittype","newadd");
                    switch (drawfeatures.getGeometry().getType())
                    {
                        case "Point":
                        case "MultiPoint":
                            editFeatures.point.addFeaures.push(drawfeatures);
                            break;
                        case "LineString":
                        case "LinearRing":
                        case "MultiLineString":
                            editFeatures.line.addFeaures.push(drawfeatures);
                            break;
                        case "Polygon":
                        case "MultiPolygon":
                            editFeatures.polygon.addFeaures.push(drawfeatures);
                            break;
                    }
                }
                if (!draw.getActive()) {
                    draw.setActive(true);
                }
            });
            map.addInteraction(draw);
        }
    };
//如果不是编辑则隐藏编辑按钮
    if (isedit) {
        $('#rgt').hide();
    }
    else {
        var features = vectSource.getFeatures();
        if (features.length > 0) {
            var defaultValue = features[0].getGeometry().getType();
            addInteraction(defaultValue);
        }
        else {
            addInteraction("None");
        }
    }
    //提交绘制的要素
    var format=new ol.format.WFS();
    function savedraw() {
        if(editFeatures){
            for(var geometryType in editFeatures) {
                var editDatas = editFeatures[geometryType];
                var addData;
                var deleteData;
                var editedata;
                var updateFeatures=[];
                for (var editType in editDatas) {
                    switch (editType) {
                        case "addFeaures":
                            addData = editDatas[editType];
                            break;
                        case "deleteFeatures":
                            deleteData = editDatas[editType];
                            break;
                        case "editeFeatures":
                            editedata = editDatas[editType];
                            if(editedata.length>0){
                                for(var i=0;i<editedata.length;i++) {
                                    var updateFeature = editedata[i].clone();
                                    updateFeature.setId(editedata[i].getId());
                                    var geometry3857=updateFeature.getGeometry().clone();
                                    //updateFeature.set("geom",geometry3857.transform(new ol.proj.Projection({code:"EPSG:3857"}),new ol.proj.Projection({code:"EPSG:4326"})));
                                    updateFeature.set("geom",geometry3857);
                                    updateFeature.setGeometryName("geom");
                                    updateFeature.unset("geometry");
                                    updateFeatures.push(updateFeature);
                                }
                            }
                            break;
                    }
                }
                if (addData.length > 0 || deleteData.length > 0 || updateFeatures.length > 0) {
                    var node = format.writeTransaction(addData.length>0?addData:null, updateFeatures.length>0?updateFeatures:null, deleteData.length>0?deleteData:null, {
                        gmlOptions: {dataProjection: "EPSG:4326", featureProjection: "EPSG:3857"},
                        featureNS: mapUrls.editMap.featureNS,
                        featureType: mapUrls.editMap.layers.geometryType[geometryType],
                        featurePrefix: mapUrls.editMap.featurePrefix,
                    });
                    console.log(node);
                    var xmldata = new XMLSerializer().serializeToString(node);
                    console.log(xmldata);
                    $.ajax({
                        type: "POST",
                        url: mapUrls.editMap.url,
                        dataType: 'xml',
                        processData: false,
                        data: xmldata,
                        contentType: 'text/xml',
                        success: function (data) {
                            console.log(data);
                        },
                        error: function (e) {
                            var errorMsg = e ? (e.status + ' ' + e.statusText) : "";
                            alert('Error saving this feature to GeoServer.<br><br>'
                                + errorMsg);
                        },
                        complete:function(e){
                            if(vectSource.getFeatures().length>0) {
                                if (window.parent.document.getElementById("geoJson")) {
                                    window.parent.document.getElementById("geoJson").value = "true";
                                }
                            }
                            else {
                                if (window.parent.document.getElementById("geoJson")) {
                                    window.parent.document.getElementById("geoJson").value = "false";
                                }
                            }
                            top.$.jBox.close(true)
                        },
                        context: this
                    });
                }
            }
        };

    };

     //界面操作代码
    $(function () {
        //输入框
        $('#shuru').bind('input propertychange', function () {
            var z = $("#shuru").val();
            if (z == "") {
                $("#del").hide();
            } else {
                $("#del").show();
            }
        });
        $("#del").click(function () {
            $("#shuru").val("");
            $(this).hide();
        });
        //固定的提示文字
        $(".r_lft a").hover(function () {
            var z = $(this).attr('data-val');
            var i = $(this).index();
            $(".r_lft .g").eq(i).find(".t").html(z);
            $(".r_lft .g").eq(i).show();
        }, function () {
            $(".r_lft .xf1").hide();
            $(".r_lft .xf2").hide();
            $(".r_lft .xf3").hide();
            $(".r_lft .xf4").hide();
            $(".r_lft .xf5").hide();
            $(".r_lft .xf6").hide();
            $(".r_lft .xf1 .t").html(" ");
            $(".r_lft .xf2 .t").html(" ");
            $(".r_lft .xf3 .t").html(" ");
            $(".r_lft .xf4 .t").html(" ");
            $(".r_lft .xf5 .t").html(" ");
            $(".r_lft .xf6 .t").html(" ");
        });
        //悬浮提示文字
        function xfts() {
            var x = 10;
            var y = 20;
            $(".r_lft a").click(function (e) {
                    $("#xyd_ts").show();
                   var btnId= $(this).attr("data-id");
                    var z = $(this).attr('data-val');
                    var xyd_ts;
                switch (btnId){
                    case"btnAddPoint":
                        $("#xyd_ts").html("提示: " + z + "，点击绘制");
                        xyd_ts = "<div id='xyd_ts'>" + "提示: " + z + "，点击绘制" + "</div>";
                        map.removeInteraction(select);
                        map.removeInteraction(modify);
                        map.removeInteraction(draw);
                        addInteraction("Point");
                        break;
                    case "btnAddLine":
                        $("#xyd_ts").html("提示: " + z + "，双击结束绘制");
                        xyd_ts = "<div id='xyd_ts'>" + "提示: " + z + "，双击结束绘制" + "</div>";
                        map.removeInteraction(select);
                        map.removeInteraction(modify);
                        map.removeInteraction(draw);
                        addInteraction("MultiLineString");
                        break;
                    case "btnAddPolygon":
                        $("#xyd_ts").html("提示: " + z + "，双击结束绘制");
                        xyd_ts = "<div id='xyd_ts'>" + "提示: " + z + "，双击结束绘制" + "</div>";
                        map.removeInteraction(select);
                        map.removeInteraction(modify);
                        map.removeInteraction(draw);
                        addInteraction("MultiPolygon");
                        break;
                    case"btnSelect":
                        $("#xyd_ts").html("提示: 点击要素进行选择");
                        xyd_ts = "<div id='xyd_ts'>" + "提示: 点击要素进行选择</div>";
                        map.removeInteraction(select);
                        map.removeInteraction(modify);
                        map.removeInteraction(draw);
                        map.addInteraction(select);
                        select.un("select",deleteSelect)
                        break;
                    case "btnModify":
                        $("#xyd_ts").html("提示:点击选择要素后进行修改");
                        xyd_ts = "<div id='xyd_ts'>" + "提示:点击选择要素后进行修改</div>";
                        map.removeInteraction(select);
                        map.removeInteraction(modify);
                        map.removeInteraction(draw);
                        map.addInteraction(modify);
                        map.addInteraction(select);
                        select.un("select",deleteSelect)
                        break;
                    case "btnDelete":
                        $("#xyd_ts").html("提示:点击选择要删除的要素");
                        xyd_ts = "<div id='xyd_ts'>" + "提示: 点击选择要删除的要素 </div>";
                        select.getFeatures().clear();
                        map.removeInteraction(select);
                        map.addInteraction(select);
                        select.on("select",deleteSelect);
                        break;
                }
                    $("body").append(xyd_ts);
                },

                function (e) {
                    $("#xyd_ts").remove()
                });

            $("canvas").mousemove(function (e) {
                $("#xyd_ts").css({
                    "top": e.pageY + y,
                    "left": e.pageX + x
                })
            });

            //悬浮文字显示判断
            $(".so").hover(function () {
                $("#xyd_ts").css("visibility", "hidden");
            }, function () {
                $("#xyd_ts").css("visibility", "visible");
            });
            $(".rgt .r_lft").hover(function () {
                $("#xyd_ts").css("visibility", "hidden");
            }, function () {
                $("#xyd_ts").css("visibility", "visible");
            });
            $(".rgt .r_rgt").hover(function () {
                $("#xyd_ts").css("visibility", "hidden");
            }, function () {
                $("#xyd_ts").css("visibility", "visible");
            });
        };
        xfts();
         //提交按钮事件
        document.getElementById("r_rgt").onclick = function () {
            savedraw()
        };
        //地图搜索事件
        var searchsource;
        var searchlayer;
        document.getElementById("tj").onclick = function () {
            var queryText = document.getElementById("shuru").value;
            if (queryText) {
                searchsource = new ol.source.Vector();
                searchlayer = new ol.layer.Vector({
                    source: searchsource,
                    style: styleFunction
                });
                var f = ol.format.ogc.filter;
                var featureRequest = new ol.format.WFS().writeGetFeature({
                    srsName: 'EPSG:4326',
                    featureNS:mapUrls.queryMap.featureNS,
                    featurePrefix: mapUrls.queryMap.featurePrefixs,
                    featureTypes: mapUrls.queryMap.layers.layerNames,
                    outputFormat: 'application/json',
                    filter: f.like( mapUrls.queryMap.queryFieldName, "*"+queryText+"*")
                });
                // post请求，并根据请求的数据进行加�
                fetch(mapUrls.queryMap.url, {
                    method: 'POST',
                    body: new XMLSerializer().serializeToString(featureRequest)
                }).then(function (response) {
                    return response.json();
                }).then(function (json) {
                    var features = new ol.format.GeoJSON().readFeatures(json, {featureProjection: 'EPSG:3857',dataProjection: "EPSG:4326"});
                    searchsource.addFeatures(features);
                    if (features.length > 0) {
                        map.getView().fit(searchsource.getExtent(), (map.getSize()));
                    }
                });
                map.addLayer(searchlayer);
            }
        };
        //清除事件
        document.getElementById("del").onclick = function () {
            if (searchlayer) {
                source.clear();
                map.removeLayer(searchlayer);
            }
        }
    });
    function deleteSelect(e){
            RemoveFeatures(e.selected);
            select.getFeatures().clear();
        };
        //删除要素
     function  RemoveFeatures(features){
            if(features) {
                    for(var i=0;i<features.length;i++){
                        var editFeature=features[i];
                        //先编辑的，需要删除编辑数组里面的相应信息
                        if(!editFeature.get("data-edittype")&&editFeature.get("data-edittype")=="newadd"){
                            switch(editFeature.getGeometry().getType()) {
                                case "Point":
                                case "MultiPoint":
                                    editFeatures.point.addFeaures.RemoveFeature(editFeature);
                                    break;
                                case "LineString":
                                case "LinearRing":
                                case "MultiLineString":
                                    editFeatures.line.addFeaures.RemoveFeature(editFeature);
                                    break;
                                case "Polygon":
                                case "MultiPolygon":
                                    editFeatures.polygon.addFeaures.RemoveFeature(editFeature);
                                    break;
                            }
                        }
                        //原来的数据，则需要删除记录，以便删除数据中的
                        else{
                            editFeature.set('geom',editFeature.getGeometry());
                            switch(editFeature.getGeometry().getType()){
                                case "Point":
                                case "MultiPoint":
                                    editFeatures.point.deleteFeatures.push(editFeature);
                                    break;
                                case "LineString":
                                case "LinearRing":
                                case "MultiLineString":
                                    editFeatures.line.deleteFeatures.push(editFeature);
                                    break;
                                case "Polygon":
                                case "MultiPolygon":
                                    editFeatures.polygon.deleteFeatures.push(editFeature);
                                    break;
                            }
                        }
                        //移除地图上的要素
                        vectSource.removeFeature(editFeature);
                        vectSource.refresh();
                    }
            }
        };
    //生成唯一编码
    function newGuid(){
        var guid = "";
        for (var i = 1; i <= 32; i++){
            var n = Math.floor(Math.random()*16.0).toString(16);
            guid +=   n;
            if((i==8)||(i==12)||(i==16)||(i==20))
                guid += "-";
        }
        return guid;
    };
    Array.prototype.RemoveFeature=function(feature){
        for(var i=0; i<this.length; i++) {
            if(this[i].getId == feature.getId()) {
                this.splice(i, 1);
                break;
            }
        }
    };

}());

